package lol.clann.minecraft.springboot.plugin.bukkit.impl;

import lol.clann.minecraft.springboot.api.bukkit.utils.EntityUtils;
import lol.clann.minecraft.springboot.api.bukkit.utils.NBTUtils;
import lol.clann.minecraft.springboot.api.bukkit.utils.WorldUtils;
import lol.clann.minecraft.springboot.api.model.reflect.FieldInvoker;
import lol.clann.minecraft.springboot.bukkit.plugin.AdapterContext;
import lol.clann.minecraft.springboot.bukkit.utils.NMSClasses;
import lol.clann.minecraft.springboot.bukkit.utils.NMSReflectUtils;
import lombok.extern.slf4j.Slf4j;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.util.Vector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;

/**
 * @author pyz
 * @date 2018/8/5 上午9:04
 */
@Slf4j
public abstract class EntityUtilsImpl implements EntityUtils {
    protected FieldInvoker fromMobSpawner;
    @Autowired
    protected NBTUtils nbtUtils;
    @Value("${bukkit.version.number}")
    protected int version;
    @Autowired
    protected WorldUtils worldUtils;

    @PostConstruct
    private void init() throws NoSuchFieldException, NoSuchMethodException {
        if (AdapterContext.isSpigot()) {
            try {
                fromMobSpawner = new FieldInvoker(NMSReflectUtils.getField(NMSClasses.getEntity(), "fromMobSpawner"));
            } catch (RuntimeException e) {
                LOGGER.warn("fail to find field fromMobSpawner in class {}. It should not happen in spigot.", NMSClasses.getEntity().getName());
            }
        }
    }

    @Override
    public void setFronzen(Entity entity, boolean fronzen) {
        if (fromMobSpawner != null) {
            fromMobSpawner.set(toNMS(entity), fronzen);
        }
    }

    @Override
    public Entity getTargetEntity(LivingEntity entity, float distance) {
        if (entity == null) {
            return null;
        }
//         位置
        Location loc = entity.getEyeLocation();
//        方向
        Vector direction = loc.getDirection();
//        搜索准星实体
        Entity result = worldUtils.rayTraceEntity(
                loc,
                direction,
                distance,
                e -> e instanceof LivingEntity && isCollidable((LivingEntity) e) && e.getEntityId() != entity.getEntityId());
        return result;
    }

    @Override
    public boolean isCollidable(LivingEntity livingEntity) {
        return true;
    }

}
